package spring.boot.shiro.filter;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 * 自定义拦截器，继承AccessControlFilter，重写两个抽象方法
 * isAccessAllowed 返回值为false继续执行onAccessDenied方法
 * 返回值为true时调用结束
 */
public class MyFilter extends AccessControlFilter {
    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) throws Exception {
        System.out.println("$$$$$$$$$$$$$$isAccessAllowed$$$$$$$$$$$$$$$$$");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        Subject subject = SecurityUtils.getSubject();
        System.out.println("ispermission"+":::::"+subject.isPermitted(request.getServletPath()));
        return subject.isPermitted(request.getServletPath());
    }

    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        System.out.println("$$$$$$$$$$$$$$onAccessDenied$$$$$$$$$$$$$$$$$");
        //请求失败时进入此方法，重定向到无权限访问页面
        WebUtils.issueRedirect(servletRequest,servletResponse,"/unauth");
        return false;
    }
}
